-- @Author: anchen
-- @Date:   2019-11-28 18:35:57
-- @Last Modified by:   anchen
-- @Last Modified time: 2020-04-17 13:50:09
-- @Description: 消息的处理

local skynet = require "skynet"
local error_code = require("error_code")
local reason = require "reason"
local constant = require "constant"
local table_insert = table.insert
local string_split = string.split
local math_random = math.random
local table_sort = table.sort
local table_remove = table.remove
---------------------------------------------------------
-- class
---------------------------------------------------------
local MessageHandler = class("MessageHandler")

function MessageHandler:ctor(message_dispatch)
    self.message_dispatch = message_dispatch
    self.desk = nil
    self:register()
end

--注册本服务里的消息
function MessageHandler:register()
    self.message_dispatch:registerSelf('REQ_AUTO_SEND',handler(self,self.autoSendReq))        --请求自动发红包
    self.message_dispatch:registerSelf('REQ_SEND_PACKET',handler(self,self.sendPacketReq))      --发红包
    self.message_dispatch:registerSelf('REQ_ROB_PACKET',handler(self,self.robPacketReq))       --抢红包
    self.message_dispatch:registerSelf('REQ_RECORD',handler(self,self.recordReq))           --我的战绩
    self.message_dispatch:registerSelf('REQ_REVOKE_PACKET',handler(self,self.revokePacketReq))           --撤销红包
    self.message_dispatch:registerSelf('REQ_PACKET_INFO',handler(self,self.packetInfoReq))           --请求红包列表信息
    self.message_dispatch:registerSelf('REQ_PLAYER_LIST',handler(self,self.playerListReq))           --请求玩家列表
    self.message_dispatch:registerSelf('REQ_REVOKE_LIST',handler(self,self.revokeListReq))           --请求取消红包列表    
end

--初始化
function MessageHandler:start()
    self.room_config = global.room_config
    self.user_manager = global.user_manager
    self.desk = global.desk
    self.table_id = self.room_config:getTableId()
    self.table_type = self.room_config:getTableType()
    self.table_gid = self.room_config:getTableGid()
    self.game_type = self.room_config:getGameType()
end

--请求自动发红包
function MessageHandler:autoSendReq(uid, fd, msg)
    local is_auto = msg.is_auto
    if is_auto == true then
        self.desk:InfiniteSendPacket(uid)
    else
        self.desk:revokeAutoSendPacket(uid)
    end
    self.desk:sendToUser(uid, "hbsl.RSP_AUTO_SEND", {result = 0,is_auto = is_auto})
    return true
end

--发红包
function MessageHandler:sendPacketReq(uid, fd, msg)
    
    local coins = msg.coins
    local lei_number = msg.thunder_number
    if lei_number < 0 then
        lei_number = math_random(0,9)
    end
    local count = msg.count 
    dbglog("sendPacketReq",uid,coins, lei_number, count)
    local user = self.user_manager:getUser(uid)
    if not user or not user:isFD(fd) then --玩家不在这个桌子里
        errlog(uid,'_____sendPacketReq但玩家不在这个桌子里______invalid status', fd)
        self.desk:sendToUser(uid, "hbsl.RSP_SEND_PACKET", {result=error_code.NO_SUCH_PLAYER})
        return true
    end

    if user:getCoins() < coins then
        errlog("coins error ",user:getCoins(),"coins:",coins)
        --金币不足
        self.desk:sendToUser(uid, "hbsl.RSP_SEND_PACKET", {result=error_code.GOLD_IS_NOT_ENOUGH})
        return false
    end

    local room_data = self.room_config:getRoomData()
    local robot_data = self.room_config:getRobotData()
    if coins < room_data.hb_coins_range[1] or coins > room_data.hb_coins_range[2] then
        errlog(uid,'sendPacketReq coins',coins,room_data.hb_coins_range)
        self.desk:sendToUser(uid, "hbsl.RSP_SEND_PACKET", {result=error_code.BET_FAIL})
        return false
    end

    --是否多发红包
    if count > 1 then
        self.desk:autoSendPacket(uid,count,coins,lei_number)
        self.desk:sendToUser(uid,'hbsl.RSP_SEND_PACKET',{result = 0,count = count})
        return true
    end


    --去扣钱
    local ret = self.desk:reduceChip(uid, coins, reason.BET_COIN)    
    if not ret then
        self.desk:sendToUser(uid,'hbsl.RSP_SEND_PACKET',{result = error_code.GOLD_IS_NOT_ENOUGH})
        return false
    end

    --这里先通知每个人自身金币发生变化
    self.desk:ntMoneyChangeToUser(uid)        
    self.desk:ntMoneyChangeToHall(uid, user:getCoins(), constant.MONEY_CHANGED_REASON.HBSL_SEND)   
    local packet_info = self.desk:sendPacket(uid,lei_number,coins,user:getIsRobot())

    self.desk:sendToUser(uid,'hbsl.RSP_SEND_PACKET',{result = 0,count = count})
    -- self.desk:sendToOther("hbsl.NTF_SEND_PACKET", uid, {packet_info=packet_info})
    return true
end

--抢红包
function MessageHandler:robPacketReq(uid, fd, msg)
    local user = self.user_manager:getUser(uid)
    if not user or not user:isFD(fd) then --玩家不在这个桌子里
        errlog(uid,'_____sendPacketReq但玩家不在这个桌子里______invalid status', fd)
        return true
    end

    local state = self.desk:getState()
    if state~="startgame" then 
        print("_____桌子不在游戏状态不可以抢红包",state)        
        return true
    end

    -- 是否可以抢红包
    local ok,ret = self.desk:canRobPacket(uid,user:getCoins())
    if not ok then
        dbglog("不能抢红包 ret:",ret,"coins",user:getCoins())
        self.desk:sendToUser(uid,'hbsl.RSP_ROB_PACKET',{result = ret})
        return true
    end

    local ok,result_coins,index,is_thunder = self.desk:robPacket(uid,user:getIsRobot())
    if not ok then
        self.desk:sendToUser(uid,'hbsl.RSP_ROB_PACKET',{result = error_code.GOLD_IS_NOT_ENOUGH})
        return true
    end

    user:setBeted(true)
--    dbglog("setBeted true",uid)
    local palyer_info = self.desk:getPlayerInfo(uid)

    dbglog("result_coins",result_coins,"index",index,"is_thunder",is_thunder)
    self.desk:sendToUser(uid,'hbsl.RSP_ROB_PACKET',{result = 0,money = result_coins,id = index,is_thunder = is_thunder})
    self.desk:sendToOther("hbsl.NTF_ROB_PACKET", uid, {player=palyer_info,id = index})

    self.desk:checkPacketNum()
        
    return true
end

--我的战绩
function MessageHandler:recordReq(uid, fd, msg)
    dbglog("recordReq uid:",uid)
    local send_info = self.desk:getFhbRecord(uid)
    local rob_info = self.desk:getQhbRecord(uid)
    local ret = {
        result = 0,
        send_info = send_info,
        rob_info = rob_info,
    }
    dbglog("recordReq:",tostring_r(ret))
    self.desk:sendToUser(uid,'hbsl.RSP_RECORD',ret)
    return true
end

--撤销红包
function MessageHandler:revokePacketReq(uid, fd, msg)
    local packet_id = msg.packet_id
    dbglog(msg)
    local packet_info,info = self.desk:revokePacket(uid,msg.packet_id,msg.group_id)

    self.desk:sendToUser(uid,'hbsl.RSP_REVOKE_PACKET',{result = 0,packet_id = packet_id,packet_info = packet_info,info = info})  
    return true 
end

--红包列表
function MessageHandler:packetInfoReq(uid, fd, msg)
    local param = msg.param

    local packet_info = self.desk:getPacketInfo(uid,param)
    dbglog("packetInfoReq",tostring_r(packet_info))
    self.desk:sendToUser(uid,'hbsl.RSP_PACKET_INFO',{result = 0 ,packet_info = packet_info,param = param})
    return true
end

--玩家列表
function MessageHandler:playerListReq(uid,fd,msg)
    dbglog("playerListReq")
    local user = self.user_manager:getUserInfo(uid)
    if not user or not user:isFD(fd) then --玩家不在这个桌子里
        errlog(uid,'_____playerListReq，但玩家不在这个桌子里______invalid status',user:getFD(), fd)
        return false
    end

    local rsp_player_info_list = {}
    local user_list = self.user_manager:getUserList()

    for uid, user in pairs(user_list) do
        local rsp_player_info = self.desk:getHbslClientInfo(user)
        table_insert(rsp_player_info_list, rsp_player_info)
    end 

    --发红包金额→避雷数→玩牌局数
    table_sort(rsp_player_info_list,function(a,b)
        if a.total_bet ~= b.total_bet then
            return a.total_bet > b.total_bet
        elseif a.win_count ~= b.win_count then
            return a.win_count > b.win_count
        else
            return a.play_count < b.play_count
        end
    end)

    local fuhao = {}
    local luck = {}

    for i,v in pairs(rsp_player_info_list) do
        if v.coins >= (fuhao.coins or 0) then
            fuhao = v
        end
        if v.win_count >= (luck.win_count or 0) then
            luck = v
        end
    end
    -- table_insert(rsp_player_info_list,1,fuhao)
    table_insert(rsp_player_info_list,1,luck)


    self.desk:sendToUser(uid,'table.RSP_PLAYER_LIST',{
        players = rsp_player_info_list
    })

    return true
end

--取消红包列表
function MessageHandler:revokeListReq(uid,fd,msg)
    dbglog("revokeListReq")
    local user = self.user_manager:getUserInfo(uid)
    if not user or not user:isFD(fd) then --玩家不在这个桌子里
        errlog(uid,'_____playerListReq，但玩家不在这个桌子里______invalid status',user:getFD(), fd)
        return false
    end

    local info = self.desk:revokeList(uid,user)
    dbglog("revokeListReq",tostring_r(info))
    self.desk:sendToUser(uid,'hbsl.RSP_REVOKE_LIST',{result = 0 ,info = info})
end

return MessageHandler
